
import React, { useState, useRef, useEffect } from 'react'
import { Layout, Input, message, Table, Button, Modal, Select, Space } from 'antd'
import { CloseOutlined } from '@ant-design/icons'
import cont from '../assets/js/cont'
import lay from '../assets/css/layout.module.css'
import log from '../assets/css/login.module.css'
import project from '../assets/css/project.module.css'
import { useNavigate } from 'react-router-dom'
import axios from '../axios/index'
import AddProject from '../action/AddProject'
import EditProject from '../action/EditProject'
import DetailProject from '../action/DetailProject'
import louyu from '../assets/css/louyu.module.css'
import detailProject from '../assets/css/detailProject.module.css'
import Comp from '../action/Comp'
// 显示子组件的内容，需要引入Outlet组件
import { Outlet } from 'react-router-dom'
// 解构出布局组件
const { Header, Footer, Sider, Content } = Layout
import { CaretDownOutlined, DownOutlined } from '@ant-design/icons'
export default function Mylalout() {
  // 验证码
  let [code, setCode] = useState('');
  let [num, setNum] = useState(60);
  let [newPhone, setNewPhone] = useState('');
  let [boolean, setBoolean] = useState(false)
  let [password, setPassword] = useState('')
  let [old, setOld] = useState('');
  let [newPass, setNew] = useState('');
  let [newWord, setWord] = useState('');
  // 当旧密码输入错误时显示
  let [bool, setBool] = useState(false);
  let [showPhone, setPhone] = useState(false);
  let nav = useNavigate();
  // 显示更改手机，更改密码
  let [bol, setBol] = useState(false);
  let [showPass, setPass] = useState(false)
  const draggleRef = useRef(null);
  let phone = localStorage.getItem('phone')

  let [show, setShow] = useState(false)
  let [edit, setEdit] = useState(false)
  let [detail, setDetail] = useState(false)
  let [myProject, setMyProject] = useState([])
  let [item, setItem] = useState({})
  let [toItem, setToItem] = useState({})
  let [showSattf, setShowSattf] = useState(false)
  let [dataSource, setDataSource] = useState([])
  const [isModalOpen, setIsModalOpen] = useState(false);
  let [id, setId] = useState('')
  let [add, setAdd] = useState(false)
  let [name, setName] = useState('')
  let [admin, setAdmin] = useState('')
  let [permission, setPermission] = useState(false)
  let [save, setSave] = useState(true)
  let [id1, setId1] = useState('')

  useEffect(() => {
    if (boolean) {
      setTimeout(() => {
        setNum(num - 1);
        if (num == 0) {
          setNum(60);
          setBoolean(false)
          setCode('')
          return;
        }
      }, 1000);
    }
  })


  // 退出登录
  function quitHan() {
    localStorage.removeItem('phone')
    localStorage.removeItem('token')
    nav('/login')
  }


  // 更改手机号

  // 正则判断手机号
  function isValidPhoneNumber(phoneNumber) {
    const regex = /^(13[0-9]|14[57]|15[012356789]|16[256]|17[0-9]|18[0-9]|19[0-9])\d{8}$/;
    return regex.test(phoneNumber);
  }

  // 验证手机号
  function verPhone() {
    if (!isValidPhoneNumber(newPhone)) {
      message.info('请输入正确的手机号')
    }
  }
  // 点击验证码，判断手机号是否为空，请求数据获得验证码
  function verCode() {
    if (newPhone == '') {
      message.info('请输入手机号')
      return;
    }
    axios.post('/api/code').then(res => {
      console.log(res);
      setCode(res.code)
      setBoolean(true)

    })
  }
  // 点击确认更换
  function editPhone() {
    if (newPhone == '' || code == '' || newPass == '') {
      message.info('请输入完整字段')
      return;
    }
    if (password != newPass) {
      message.info('登陆密码错误');
      return;
    }
    axios.post('/api/phone', {
      phone: phone,
      newPhone: newPhone
    }).then(res => {
      console.log(res);
      message.info('手机号更改完成！')
      localStorage.setItem('phone', newPhone)
      setNew('');
      setNewPhone('');
      setCode('')
      setPhone(false)
      setBol(false)

    })
  }

  // 图片
  function getImg(url) {
    return new URL(url, import.meta.url).href;
  }

  // 更改密码

  function getPass() {

    axios.put('/api/repass', {
      phone: phone
    }).then(res => {

      setPassword(res.data[0].password)
    })
  }
  // 输入旧密码
  function oldHan() {
    if (password != old) {
      setBool(true)
    } else {
      setBool(false)
    }
  }
  // 判断密码
  function isValidPassword(password) {
    const regex = /^(?=.*[a-zA-Z])(?=.*\d)[A-Za-z\d]{8,20}$/;
    return regex.test(password);
  }
  // 输入新密码
  function newHan() {
    if (old == '') {
      message.info('请输入旧密码')
      return;
    }
    if (!isValidPassword(newPass)) {
      message.info('请输入包含字母和数字在内的8-20位密码');
      return;
    }
  }
  // 重新输入密码
  function reNewHan() {
    if (old == '') {
      message.info('请输入旧密码')
      return;
    }
    if (newPass == '') {
      message.info('请输入新密码')
      return;
    }
    if (newPass != newWord) {
      message.info('两次密码不一致')
      return;
    }
  }
  // 点击确认修改
  function editHan() {
    if (old == '' || newPass == '' || newWord == '') {
      message.info('请输入完整字段')
      return;
    }
    axios.put('/api/password', {
      phone: phone,
      password: newPass
    }).then(res => {
      console.log(res);
      setPass(false)
      setOld('');
      setNew('');
      setWord('')
    })
  }

  // 获取项目列表
  const getData = () => {
    axios.get('/api/project').then((res) => {
      console.log(res.data);
      setMyProject(res.data)
    })
  }

  // 渲染项目数据
  useEffect(() => {
    getData()
  }, [])

  // 编辑项目
  const editProject = (item) => {
    setEdit(true)
    console.log(item);
    setItem(item)
  }

  // 查看项目详情
  const toProject = (item) => {
    setDetail(true)
    console.log(item);
    setToItem(item)
  }

  // 加入项目
  const accept = (id) => {
    axios.put('/api/project/join', {
      id: id
    }).then((res) => {
      console.log(res);
      getData()
    })

  }

  // 删除项目
  const deleteProject = (id) => {
    axios.delete('/api/project/del', {
      params: {
        id: id
      }
    }).then((res) => {
      console.log(res);
      getData()
    })
  }

  // 点击人员管理
  const manageSattf = () => {
    setShowSattf(true)
    setDetail(false)
    getSattf()
  }

  // 点击删除
  const delStaff = (id) => {
    setIsModalOpen(true)
    setId(id)
  }

  // 删除人员
  const handleOk = () => {
    setIsModalOpen(false);

    axios.delete('/api/staff/del', {
      params: {
        id: id
      }
    }).then((res) => {
      console.log(res);
      getSattf()
    })
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // 添加人员
  const addSattf = () => {
    if (name == '' || admin == '') {
      warning1()
      return
    } else {
      axios.post('/api/staff/add', {
        name: name,
        admin: admin
      }).then((res) => {
        console.log(res);
        getSattf()
        setAdd(false)
        success1()
        setAdmin('')
        setName('')
      })
    }
  }

  // 修改人员名字
  const editName = (index, name) => {
    console.log(id);
    setName(name)
    setId1(index)
  }

  // 保存人员名字
  const editSattf = () => {
    if (name == '') {
      warning()
      return
    } else {
      axios.put('/api/staff/edit', {
        id: id1,
        name: name
      }).then((res) => {
        getSattf()
        success()
        setId1('')
        setName('')
      })
    }
  }

  // 填写提示框
  const warning = () => {
    message.open({
      type: 'warning',
      content: '请填写修改内容....',
    });
  };

  // 新建成功提示框
  const success = () => {
    message.open({
      type: 'success',
      content: '人员名称修改成功！',
    });
  };

  // 输入提示框
  const warning1 = () => {
    message.open({
      type: 'warning',
      content: '请输入内容....',
    });
  };

  // 新建成功提示框
  const success1 = () => {
    message.open({
      type: 'success',
      content: '人员添加成功！',
    });
  };

  // 人员列表
  const columns = [
    {
      title: '登录账号 ',
      key: 'admin',
      render: (item, row) => (
        <span className={project.peopleAdmin}>
          <span>{row.admin}</span>
          {row.msg == 1 && <div className={project.massage}>管理员</div>}
        </span>
      ),
    },
    {
      title: '备注姓名',
      key: 'name',
      render: (item, row) => (
        <span className={project.peopleName}>
          {id1 != row.id
            ? <div>
              <span>{row.name}</span>
              <img src={getImg('../assets/images/edita.png')} alt="" onClick={() => { editName(row.id, row.name) }} />
            </div>
            : <div className={detailProject.save1}>
              <div>
                <input type="text" value={name} onChange={(e) => { setName(e.target.value) }} />
              </div>
              <div onClick={() => { editSattf(row.id) }} style={{cursor:'pointer'}}>保存</div>
            </div>
          }
        </span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
    },
    {
      title: '操作',
      key: 'action',
      render: (row) => (
        <span className={project.action}>
          <Button type='text' className={row.state == '未激活' ? project.state : ''} disabled={row.state != '未激活' ? true : false} onClick={() => { setPermission(true) }}>{row.state != '正常' && '权限'}</Button>
          <Button type='text' className={project.delete} onClick={() => { delStaff(row.id) }}>{row.state == '正常' ? '' : '删除'}</Button>
        </span>
      ),
    }
  ]

  // 获取人员信息
  let getSattf = () => {
    axios.get('/api/staff').then((res) => {
      console.log(res.data);
      setDataSource(res.data)
    })
  }

  return (
    <cont.Provider
      value={{
        change: () => {
          setShow(false)
        },
        editChange: () => {
          setEdit(false)
        },
        detailChange: () => {
          setDetail(false)
        }
      }}
    >
      <div className={project.project}>
        <Layout>
          <Header className={lay.header}>
            <div className={lay.left}>
              <img src={getImg('../assets/images/logo.png')} alt="" onClick={() => {
                nav('/home/assets/build')
              }} />
            </div>
            <div className={lay.right} onClick={() => {
              setBol(!bol)
            }}>
              <p>{phone}</p>
              <DownOutlined style={{
                color: '#fff',
                fontSize: '10px'
              }} />
              {bol ? <div className={lay.model} >
                <p onClick={() => {
                  setPass(true)
                  getPass()
                }}>更改密码</p>
                <p onClick={() => {
                  getPass()
                  setPhone(true)
                }}>更换手机号</p>
                <p onClick={() => {
                  quitHan()
                }}>退出登录</p>
              </div> : <p style={{
                padding: 0,
                margin: 0
              }}></p>}

            </div>
            {showPass && <div className={lay.fixed}>
              <div className={lay.modelCon} >
                <div className={lay.modalTop}>
                  <p>修改密码</p>
                  <CloseOutlined onClick={() => {
                    setPass(false)
                    setBol(false)
                  }} />
                </div>
                <Input.Password
                  placeholder='请输入旧密码'
                  className={bool ? `${lay.passInput} ${lay.pass}` : `${lay.passInput}`}
                  value={old} onChange={(e) => {
                    setOld(e.target.value)
                  }} onBlur={() => {
                    oldHan()
                  }} />
                {bool && <p style={{
                  fontSize: 12, color: '#F97171',
                  padding: 0
                }}>旧密码输入错误</p>}
                <Input.Password
                  placeholder='请输入新密码，包含数字和字母的8~20位密码'
                  value={newPass}
                  className={lay.passInput}
                  onChange={(e) => {
                    setNew(e.target.value)
                  }} onBlur={() => {
                    newHan()
                  }} />
                <Input.Password
                  placeholder='请输入旧密码'
                  value={newWord}
                  className={lay.passInput}
                  onChange={(e) => {
                    setWord(e.target.value)
                  }}
                  onBlur={() => {
                    reNewHan()
                  }}
                />
                <button className={lay.btn} style={{
                  marginTop: 20
                }}
                  onClick={() => {
                    editHan()
                  }}
                >确认修改</button>
              </div></div>
            }
            {showPhone && <div className={lay.fixed}>
              <div className={lay.modelCon} >
                <div className={lay.modalTop}>
                  <p>更换手机号</p>
                  <CloseOutlined onClick={() => {
                    setPhone(false)
                    setBol(false)
                  }} />
                </div>
                <div className={lay.input} style={{
                  marginTop: 20
                }}>
                  <div className={log.addr}>
                    <span>中国+86</span>
                    <DownOutlined />
                  </div>
                  <input type="text" placeholder='请输入手机号' className={lay.leftInput} value={newPhone} onChange={(e) => {
                    setNewPhone(e.target.value)

                  }} onBlur={(e) => {
                    verPhone()
                  }} />
                </div>
                <div className={lay.input}>
                  <input type="text" className={lay.code} placeholder='请输入验证码' value={code} onChange={() => { }} />
                  <div className={lay.getCode} onClick={() => {
                    verCode()
                  }} style={{
                    cursor: 'pointer'
                  }}>{boolean ? `${num}s` : '获取验证码'}</div>
                </div>
                <div className={lay.input}>
                  <input type="password" placeholder='确认密码' value={newPass} onChange={(e) => {
                    setNew(e.target.value)
                  }} />
                </div>
                <button className={lay.btn} style={{
                  marginTop: 20
                }}
                  onClick={() => {
                    editPhone()
                  }}
                >确认更换</button>
              </div></div>
            }
          </Header>
        </Layout>
        {myProject.length > 0
          ? <div className={project.content}>
            <div className={project.head}>我负责的项目</div>
            <div className={project.my}>
              {myProject.map((item, index) => {
                return (
                  <div key={item.id}> 
                    {item.my == 1 &&
                      <div className={project.myProject}>
                        <div onClick={() => { editProject(item) }}>
                          <div className={project.name}>
                            <span>{item.name}</span>
                            <img src={getImg('../assets/images/info.png')} />
                          </div>
                          <div className={project.module}>
                            <div className={item.invest == 1 ? project.zhaoshang : ''}>{item.invest == 1 ? '招商' : ''}</div>
                            <div className={item.operate == 1 ? project.yunying : ''}>{item.operate == 1 ? '运营' : ''}</div>
                          </div>
                          <div className={project.people}>{`人员(${item.num})`}&gt;</div>
                        </div>
                        <button onClick={() => { toProject(item) }}>进入项目</button>
                      </div>
                    }
                  </div>
                )
              })}
              <img src={getImg('../assets/images/new.png')} alt="" onClick={() => { setShow(true) }} />
            </div>
            <div className={project.head}>我加入的项目</div>
            <div className={project.my}>
              {myProject.map((item, index) => {
                return (
                  <div key={item.id}>
                    {item.my == 0 &&
                      <div className={project.myProject}>
                        <div className={project.name}>
                          <span>{item.name}</span>
                          <img src={getImg('../assets/images/info.png')} alt="" />
                        </div>
                        <div className={project.module}>
                          <div className={item.invest == 1 ? project.zhaoshang : ''}>{item.invest == 1 ? '招商' : ''}</div>
                          <div className={item.operate == 1 ? project.yunying : ''}>{item.operate == 1 ? '运营' : ''}</div>
                        </div>
                        <div className={project.people}>{`人员(${item.num})`}&gt;</div>
                        {item.join == 1
                          ? <button onClick={() => { toProject(item) }}>进入项目</button>
                          : <div className={project.join}>
                            <div onClick={() => { accept(item.id) }}>接受</div>
                            <div onClick={() => { deleteProject(item.id) }}>拒绝</div>
                          </div>
                        }
                      </div>
                    }
                  </div>
                )
              })}
            </div>
          </div>
          : <div className={project.nothing}>
            <img src={getImg('../assets/images/weit.png')} alt="" />
            <div>还没有您负责的项目，马上<span onClick={() => { setShow(true) }}>创建项目</span></div>
          </div>
        }
      </div>
      {showSattf && <div className={detailProject.toCover}>
        <img src={getImg('../assets/images/close.png')} alt="" onClick={() => {
          setShowSattf(false); setDetail(true)
        }} />
        <div className={detailProject.detailSattf}>
          <div className={project.itemEdit}>
            <span>项目编辑</span>
            <span onClick={() => { setAdd(true) }}>添加人员</span>
          </div>
          <div className={project.table}>
            <Table dataSource={dataSource} columns={columns} pagination={false} />
          </div>
        </div>
      </div>
      }
      {add &&
        <div className={project.toCover}>
          <div className={project.addMassage}>
            <div className={louyu.head}>
              <span>添加人员</span>
              <CloseOutlined style={{ color: "#B4B6BB" }} onClick={() => {
                setAdd(false); setName(''); setAdmin('')
              }} />
            </div>
            <div className={louyu.input}>
              <span className={louyu.fuhao}>*</span>
              <span>登录账号</span>
              <div className={project.input1}>
                <Select
                  style={{
                    width: 96,
                    height: 36
                  }}
                  placeholder='中国+86'
                  options={[
                    {
                      value: 'lucy',
                      label: 'Lucy',
                    },
                  ]}
                />
                <input placeholder='请输入' value={admin} onChange={(e) => {
                  setAdmin(e.target.value);
                }} />
              </div>
            </div>
            <div className={louyu.input}>
              <span className={louyu.fuhao}>*</span>
              <span>备注姓名</span>
              <div className={project.input2}>
                <input placeholder='请输入' value={name} onChange={(e) => {
                  setName(e.target.value);
                }} />
              </div>
            </div>
            <button onClick={() => { addSattf() }}>保存</button>
          </div>
        </div>
      }
      {permission &&
        <div className={project.toCover}>
          <div className={project.permission}>
            <div className={louyu.head}>
              <span>权限配置</span>
              <CloseOutlined style={{ color: "#B4B6BB" }} onClick={() => {
                setPermission(false)
              }} />
            </div>
            <div className={project.comp}>
              <Comp></Comp>
            </div>
            <div className={louyu.tonext}>
              <button>选择全部</button>
              <button className={louyu.next} onClick={() => { setPermission(false) }}>保存</button>
            </div>
          </div>
        </div>
      }
      <Modal title="此操作是不可恢复的！" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}
        okText="确认"
        cancelText="取消"
      >
        <p>您确认要执行此删除操作吗?</p>
      </Modal>
      {show && <AddProject getData={getData}></AddProject>}
      {edit && <EditProject item={item} getData={getData}></EditProject>}
      {detail && <DetailProject getData={getData} item={toItem} manageSattf={manageSattf}></DetailProject>}
    </cont.Provider>
  )
}
